//
//  ViewController.swift
//  DataParsing
//
//  Created by flipped on 2024/9/24.
//

import UIKit

struct Person: Codable {
  var name: String
  var age: Int
}

struct PeopleResponse: Codable {
  var people: [Person]
}

class ViewController: UIViewController {
  override func viewDidLoad() {
    super.viewDidLoad()
    // 调用函数
    // codable
    loadSimpleJSON()
    loadComplicateJSON()

    print("----parseByJSONSerilization----")

    // JSONSerialization
    parseByJSONSerilization()
    //
    print("加载本地文件的两种方式")
    urlFor()
    pathFor()
		
		print("------encoder编码成JSON----")
		encoderObjToJSONWithCodable()
  }

  func loadSimpleJSON() {
    // 使用 Bundle 来获取 JSON 文件的路径
    if let path = Bundle.main.path(forResource: "simple", ofType: "json") {
      do {
        // 读取文件内容并转为 Data 类型
        let data = try Data(contentsOf: URL(fileURLWithPath: path), options: .mappedIfSafe)

        // 使用 JSONDecoder 解码 JSON 数据
        let person = try JSONDecoder().decode(Person.self, from: data)

        // 打印解析后的结果
        print("loadSimpleJSON Name: \(person.name), Age: \(person.age)")
      } catch {
        // 处理错误
        print("Error parsing JSON: \(error)")
      }
    }
  }

  func loadComplicateJSON() {
    // 使用 Bundle 来获取 JSON 文件的路径
    if let path = Bundle.main.path(forResource: "complicate", ofType: "json") {
      do {
        // 读取文件内容并转为 Data 类型
        let data = try Data(contentsOf: URL(fileURLWithPath: path), options: .mappedIfSafe)

        // 使用 JSONDecoder 解码 JSON 数据
        let peopleResponse = try JSONDecoder().decode(PeopleResponse.self, from: data)
        // 访问数组
        for person in peopleResponse.people {
          print("loadComplicateJSON Name: \(person.name), Age: \(person.age)")
        }
      } catch {
        // 处理错误
        print("Error parsing JSON: \(error)")
      }
    }
  }
}

// MARK: - 解析的三种方式

extension ViewController {
  func parseByJSONSerilization() {
    if let url = Bundle.main.url(forResource: "simple", withExtension: "json") {
      do {
        let data = try Data(contentsOf: url)
        if let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] {
          if let name = json["name"] as? String, let age = json["age"] as? Int {
            print("parseByJSONSerilization Name: \(name), Age: \(age)")
          }
        }
      } catch {
        print("Error parsing JSON: \(error)")
      }
    }
  }
}

// MARK: - 查找项目本地资源方式有两种

extension ViewController {
  // 1. url(forResource) 推荐,方法简便
  // 2. path(forResource:) 不推荐,还需要=>URL. 字符串需处理才使用
  func urlFor() {
    if let url = Bundle.main.url(forResource: "simple", withExtension: "json") {
      do {
        let data = try Data(contentsOf: url)
        let person = try JSONDecoder().decode(Person.self, from: data)
        print(person)
      } catch {
        print("Error decoding JSON: \(error)")
      }
    }
  }

  func pathFor() {
    if let path = Bundle.main.path(forResource: "complicate", ofType: "json") {
      do {
        let url: URL!
        if #available(iOS 16, *) {
          url = URL(filePath: path, directoryHint: .notDirectory)
        } else {
          url = URL(fileURLWithPath: path)
        }
        let data = try Data(contentsOf: url)
        let peopleResponse = try JSONDecoder().decode(PeopleResponse.self, from: data)

        for people in peopleResponse.people {
          print("name:\(people.name) age:\(people.age)")
        }
      } catch {
        print("错误未处理")
      }
    }
  }
}

// MARK: - 使用codable编码(序列化)成JSON

struct Book: Codable {
  let name: String
  let author: String
  let price: Double
}

extension ViewController {
  func encoderObjToJSONWithCodable() {
    let book = Book(name: "Swift Programming Guide", author: "John Doe", price: 29.99)
    do {
      let encoder = JSONEncoder()
      let data = try encoder.encode(book)
      if let jsonString = String(data: data, encoding: .utf8) {
        print(jsonString)
      }
    } catch {
      print("Error encoding book: \(error)")
    }
  }
}
